package com.zl.cms.dao;

import com.zl.basic.CommonUtil.Check;
import com.zl.basic.dao.BaseDao;
import com.zl.basic.model.Pager;
import com.zl.cms.model.Channel;
import com.zl.cms.model.ChannelTree;
import com.zl.cms.model.Group;
import com.zl.cms.model.GroupChannel;
import org.springframework.stereotype.Repository;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * User: zl email:c3tc3tc3t@126.com Date: 14-1-14 Time: 下午12:04
 */
@Repository("groupDao")
public class GroupDao extends BaseDao<Group> implements IGroupDao {
  @Override
  public List<Group> listGroup() {
    return this.list("from Group");
  }

  @Override
  public Pager<Group> findGroup() {
    return super.find("from Group");
  }

  @Override
  public void deleteGroupUsers(int gid) {
    this.updateByHql("delete UserGroup where group.id=?", gid);
  }

  @Override
  public void addGroupChannel(Group group, Channel channel) {
    GroupChannel gc = this.loadGroupChannel(group.getId(), channel.getId());
    if (null != gc) {
      return;
    } else {
      gc = new GroupChannel();
      gc.setGroup(group);
      gc.setChannel(channel);

      this.getSession().save(gc);
    }
  }

  @Override
  public GroupChannel loadGroupChannel(int gid, int cid) {
    return (GroupChannel) this.queryObjectByHql(
        "from GroupChannel where group.id=? and channel.id=? ", new Object[] {gid, cid});
  }

  @SuppressWarnings("unchecked")
  @Override
  public List<Integer> listGroupChannelIds(int gid) {
    String hql = "select gc.channel.id from GroupChannel gc where gc.group.id=? ";

    return this.getSession().createQuery(hql).setParameter(0, gid).list();
  }

  @Override
  public Set<ChannelTree> generateGroupChannelTree(int gid) {
    String sql =
        "select c.id as id, c.name as name,c.pid as pid " + " from t_group_channel gc "
            + " left join t_channel c on gc.c_id=c.id " + " where gc.g_id = ? ";
    List<ChannelTree> cts = this.listBySql(sql, gid, ChannelTree.class, false);
    ChannelDao.initTreeNode(cts);


    return new HashSet<>(cts);

  }

  @Override
  public Set<ChannelTree> generateUserChannelTree(int uid) {

    String sql =
        "select distinct c.id as id, c.name as name,c.pid as pid " + " from t_group_channel gc "
            + "left join t_channel c on gc.c_id=c.id "
            + "left join t_user_group ug on ug.g_id = gc.g_id " + "where ug.u_id = ? ";

    List<ChannelTree> cts = this.listBySql(sql, uid, ChannelTree.class, false);
    ChannelDao.initTreeNode(cts);
    return new HashSet<>(cts);
  }

  @Override
  public void cleanGroupChannel(int gid) {
    this.updateByHql("delete GroupChannel where group.id = ?", gid);
  }

  @Override
  public void deleteGroupChannel(int gid, int cid) {

    this.updateByHql("delete GroupChannel where group.id = ? and channel.id = ? ", new Object[] {
        gid, cid});
  }
}
